package com.hadoop.practice.just_memory;

import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.NLineInputFormat;
import org.apache.hadoop.mapreduce.lib.output.NullOutputFormat;

import java.io.IOException;

/**
 * User: wujun
 * Date: 14-6-9 下午3:33
 */
public class CostMemoryJob {
    public static class TokenizerMapper
            extends Mapper<Object, Text, Text, IntWritable> {

        private final static IntWritable one = new IntWritable(1);
        private Text word = new Text();

        public void map(Object key, Text value, Context context
        ) throws IOException, InterruptedException {
            double a = 0;
            for (int i=0; i < 100; i++) {
                double b = Math.random() * i;
                a = Math.pow(2, b);
            }
            word.set(String.valueOf(a));
            context.write(word, one);
        }
    }

    public static class IntSumReducer
            extends Reducer<Text,IntWritable,Text,IntWritable> {
        private IntWritable result = new IntWritable();

        public void reduce(Text key, Iterable<IntWritable> values,
                           Context context
        ) throws IOException, InterruptedException {
            int sum = 0;
            for (IntWritable val : values) {
                sum += val.get();
            }
            result.set(sum);
            context.write(key, result);
        }
    }

    public static void main(String[] args) throws Exception {
        JobConf conf = new JobConf();
        long memoryMB = Long.parseLong(args[0]);
        conf.setMemoryForMapTask(memoryMB);
        conf.setMemoryForReduceTask(memoryMB);
        conf.setNumMapTasks(1000);
        conf.setNumReduceTasks(10);
        if (args.length > 2) {
            conf.setQueueName(args[2]);
        }

        Job job = Job.getInstance(conf, "CostMemoryJob");
        job.setJarByClass(CostMemoryJob.class);
        job.setMapperClass(TokenizerMapper.class);
        job.setCombinerClass(IntSumReducer.class);
        job.setReducerClass(IntSumReducer.class);
        job.setInputFormatClass(NLineInputFormat.class);
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(IntWritable.class);
        job.setOutputFormatClass(NullOutputFormat.class);
        FileInputFormat.addInputPath(job, new Path(args[1]));

        if (args.length > 3) {
            FileInputFormat.setMinInputSplitSize(job, Long.parseLong(args[3]));
            FileInputFormat.setMaxInputSplitSize(job, FileInputFormat.getMinSplitSize(job) + 1000);
        }

        System.exit(job.waitForCompletion(true) ? 0 : 1);
    }
}
